package com.admin.controller;

import com.admin.service.RoleService;
import com.admin.util.LogUtil;
import com.admin.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedList;
import java.util.List;

@RestController
@RequestMapping("/admin/role")
@Api(tags = "角色管理")
public class RoleController {
    @Autowired
    private RoleService roleService;
    private final Logger logger = LogUtil.getBussinessLogger();

    /**
     * 查询所有角色
     *
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("角色：列表")
    public Result list() {
        Result result = new Result();
        try {
            result.setCode(Result.Code.SUCCESS);
            result.setData(roleService.list());
            result.setCount(roleService.count());
        } catch (Exception e) {
            result.setCode(Result.Code.SYSTEMERROR);
            logger.error(e.getMessage());
        }
        return result;
    }

    /**
     * 返回角色关联菜单信息
     *
     * @return
     */
    @GetMapping("/relMenu")
    @ApiOperation("角色：关联菜单信息")
    public Result getRel(@RequestParam(value = "roleId", required = true) Long roleId) {
        Result result = new Result();
        try {
            result.setCode(Result.Code.SUCCESS);
            result.setData(roleService.relMenu(roleId));
        } catch (Exception e) {
            result.setCode(Result.Code.SYSTEMERROR);
            logger.error(e.getMessage());
        }
        return result;
    }

   /* *
     * 保存菜单与角色关联信息 //TODO 未完
     *
     * @return
     */
    @GetMapping("/addRelMenu")
    @ApiOperation("角色：保存菜单与角色关联信息")
    public Result addRelMenu(String[] menuIds, Long roleId) {
        Result result = new Result();
        try {
            result.setCode(Result.Code.SUCCESS);
            List<Long> menus = new LinkedList<>();
            for (int i = 0; i < menuIds.length; i++) {
                menus.add(Long.parseLong(menuIds[i]));
            }
            roleService.addRoleMenu(roleId, menus);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(Result.Code.SYSTEMERROR);
            logger.error(e.getMessage());
        }
        return result;
    }
}
